import 'package:english_words/english_words.dart';
import 'package:first_flutter_project/main/AfterLayoutRoute.dart';
import 'package:first_flutter_project/main/useofthreewidget/AnimatorLearing.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';

import 'CounterWidget.dart';
import 'CusStatelessWidget.dart';
import 'CusTomBaseWidget.dart';
import 'CustomBoxWidget.dart';
import 'Gesture/GestureDetectorLearing.dart';
import 'anima/AnimatorLearing.dart';
import 'class_room_test/class_room_main.dart';
import 'file/FileOperatorLearing.dart';
import 'function/FuntionWidgetTestRoute.dart';
import 'layoutlearing/LayoutOperatorLearing.dart';
import 'layoutlearing/simpleLayerDemoLearing.dart';
import 'scrooll/CustomScrollControllerTestRoute.dart';
import 'DecoratedBoxWidget.dart';
import 'scrooll/ScrollControllerDemo.dart';
import 'scrooll/ScrollbarWidget.dart';
import 'TapboxAStateManage.dart';
import '../statusmanage/WidgetStatusManage.dart';

var netWorkImageUrl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2Ftp05%2F1Z9291TIBZ6-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1644809008&t=8bf2bd00ec0da949763c644935e7c0cd";


void main() {
  runApp(MyApp());
}

var counterWidgetKey = ValueKey('CounterWidget');

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    var color; // 仅有声明未赋值的时候，这里的color的类型是dynamic,所以它的类型是可以变的
    color = 'red';
    print(color is String); //true
    color = 0xffff0000;
    print(color is int); //true

    var colorValue = 0xffff0000; //声明时并赋值，这里colorValue类型已经推导出为int,并且确定了类型
    // colorValue = 'red'; //错误，这里会抛出编译异常，String类型的值不能赋值给int类型
    // print(colorValue is int); //true

    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          // This is the theme of your application.
          //
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          primarySwatch: Colors.blue,
        ),
        // home: MyHomePage(title: 'Flutter Demo Home Page'),
        routes: {
          "new_page": (context) { return NewRoute(text: "注册路由表");},
          "new_echo_page": (context) =>
              CusStatelessWidget(text: "CusStatelessWidget界面好啊"),
          "CounterWidget": (context) =>
              CounterWidget(key: ValueKey('CounterWidget'), initValue: 0),
          "TapboxAStateManage": (context) => TapboxA(key: ValueKey('TapboxA')),
          "ParentBWidget": (context) => ParentBWidget(false),
          "CusTomBaseWidget": (context) => CusTomBaseWidget(
              key: ValueKey('CusTomBaseWidget'), introduce: "认识基础组件"),
          "CustomBoxWidget": (context) => CustomBoxWidget(
              key: ValueKey('CustomBoxWidget'), introduce: "boxzujian"),
          "DecoratedBoxWidget": (context) =>
              DecoratedBoxWidget(key: ValueKey('DecoratedBoxWidget')),
          "ScrollbarWidget": (context) =>
              ScrollbarWidget(key: ValueKey('ScrollbarWidget')),
          "WidgetStatusManage": (context) =>
              WidgetStatusManage(key: ValueKey('WidgetStatusManage')),
          "AfterLayoutRoute": (context) =>
              AfterLayoutRoute(key: ValueKey('AfterLayoutRoute')),
          "ScrollControllerDemo": (context) =>
              ScrollControllerTestRoute(),
          "CustomScrollControllerTestRoute": (context) =>
              CustomScrollControllerTestRoute(),

          "FunctionWidgetTestRoute": (context) =>
              FuntionWidgetTestRoute(),

          "GestureTestRoute": (context) =>
              GestureTestRout(),

          "AnimatorLearing": (context) =>
              AnimatorLearing(),

          "UseOfThreePartyComponents": (context) =>
              UseOfThreePartyComponents(),

          "FileOperatorLearing": (context) =>
              FileOperatorLearing(),

          "LayoutOperatorLearing": (context) =>
              LayoutOperatorLearing(),

          "SimpleLayerDemoLearing": (context) =>
              SimpleLayerDemoLearing(),

          "ClassRoomTopicPage": (context) =>
              ClassRoomTopicPage(),
          "/": (context) {
            return MyHomePage(title: 'Flutter Demo Home Page');
          }
        },
        onGenerateRoute: (RouteSettings settings) {
          return MaterialPageRoute(builder: (context) {
            String? routeName = settings.name;
            //如果因为当调用Navigator.pushNamed(...)打开命名路由时，如果指定的路由名在路由表中已注册，
            // 则会调用路由表中的builder函数来生成路由组件；
            // 如果路由表中没有注册，才会调用onGenerateRoute来生成路由

            //可做效果 如果访问的路由页需要登录，但当前未登录，则直接返回登录页路由，
            // 引导用户登录；其它情况则正常打开路由。
            print("路由返回值: onGenerateRoute");
            print("路由提示: 当前路由没注册");
            return Container();
          });
        });
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // 这个对setState的调用告诉Flutter框架有些东西已经发生了
//在此状态下更改，这将导致它重新运行下面的构建方法
//使显示能够反映更新的值。如果我们改变了
// _counter如果不调用setState()，则构建方法不会
//再次调用，因此什么也不会发生。
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
      widget.title;
      //导航到新路由
      var result =
          Navigator.push(context, MaterialPageRoute(builder: (context) {
        return NewRoute(text: "传值给新路由姐买你1-_incrementCounter");
      }));
      print("路由返回值: $result");
    });
  }

  var hintText = "open new route";

  void _openNewRouter() async {
    //导航到新路由
    var result =
        await Navigator.push(context, MaterialPageRoute(builder: (context) {
      return NewRoute(text: "传值给新路由姐买你1-_openNewRouter");
    }));
    print("路由返回值: $result");
    setState(() {
      hintText = result;
    });
  }

  //通过在MyApp中注册路由表进行跳转
  void _openNewRouterByRouterList() {
    //导航到新路由

    Navigator.pushNamed(context, "new_page", arguments: "hi");
    // Navigator.pushNamed(context, "new_page_noregi", arguments: "hi");
  }

  @override
  Widget build(BuildContext context) {
    //底部导航栏
    int _selectedIndex = 1;
    void _onItemTapped(int index) {
      setState(() {
        _selectedIndex = index;
      });
    }

    void _onAdd() {}

    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    Future<String> loadAsset() async {
      return rootBundle.loadString('images/config.json');
    }

    final wordPair = new WordPair.random();
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
          // Center is a layout widget. It takes a single child and positions it
          // in the middle of the parent.
          child: SingleChildScrollView(
            child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:$wordPair',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
            TextButton(
              child: Text("跳转至自定义的StatelessWidget界面echo"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "new_echo_page", arguments: "hi");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("跳转至自定义的CounterWidget"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "CounterWidget", arguments: "hi");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("跳转至不存在的路由"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "跳转至不存在的路由", arguments: "hi");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("跳转至Widget状态管理的界面"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "TapboxAStateManage",
                    arguments: "hi");
              } //导航到新路由
              ,
            ),
            Image.asset("images/ic_bind_card_focus.png"),
            Image(
              image: new AssetImage('images/ic_bind_card_gray.png'),
              width: 20,
            ),
            TextButton(
              child: Text(hintText),
              style: ButtonStyle(),
              onPressed: () {
                _openNewRouter();
                _openNewRouterByRouterList();
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("认识基础组件"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "CusTomBaseWidget");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("盒子布局"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "CustomBoxWidget");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("可以在其子组件绘制前(或后)绘制一些装饰（Decoration），如背景、边框、渐变等"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "DecoratedBoxWidget");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("滑动控件"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "ScrollbarWidget");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("查看状态更改"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "WidgetStatusManage");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("查看自定义控件的尺寸位置信息"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "AfterLayoutRoute");
              } //导航到新路由
              ,
            ),

            TextButton(
              child: Text("ScrollController滚动控件的滚动监听"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "ScrollControllerDemo");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("自定义滚动控件的嵌套冲突问题"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "CustomScrollControllerTestRoute");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("功能性的控件组件"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "FunctionWidgetTestRoute");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("手势控件相关"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "GestureTestRoute");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("动画控件相关"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "AnimatorLearing");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("三方组件使用"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "UseOfThreePartyComponents");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("文件操作相关"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "FileOperatorLearing");
              } //导航到新路由
              ,
            ),

            TextButton(
              child: Text("widget控件位置定义相关"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "LayoutOperatorLearing");
              } //导航到新路由
              ,
            ),

            TextButton(
              child: Text("界面模拟实战"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "ClassRoomTopicPage");
              } //导航到新路由
              ,
            ),

            TextButton(
              child: Text("Layer相关的基础知识点"),
              style: ButtonStyle(),
              onPressed: () {
                Navigator.pushNamed(context, "SimpleLayerDemoLearing");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text(
                  "要转储Widgets树的状态，请调用debugDumpApp()--debugPrint 日志打印避免过长被Android 日志系统 丢掉"),
              style: ButtonStyle(),
              onPressed: () {
                debugDumpApp();
                debugPrint("debugPrint 日志打印避免过长被Android 日志系统 丢掉");
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("如果我们尝试调试布局问题 debugDumpRenderTree()转储渲染树"),
              style: ButtonStyle(),
              onPressed: () {
                debugDumpRenderTree();
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("如果我们尝试调试合成问题，则可以使用 debugDumpLayerTree()"),
              style: ButtonStyle(
                  elevation: MaterialStateProperty.resolveWith((states) {
                return 101;
              })),
              onPressed: () {
                debugDumpLayerTree();
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text(
                  "我们还可以调用 debugDumpSemanticsTree() (opens new window)获取语义树"),
              onPressed: () {
                debugDumpSemanticsTree(DebugSemanticsDumpOrder.traversalOrder);
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text(
                  "要找出相对于帧的开始/结束事件发生的位置，可以切换debugPrintBeginFrameBanner (opens new window)"
                  "和debugPrintEndFrameBanner (opens new window)布尔值以将帧的开始和结束打印到控制台。"),
              onPressed: () {
                debugPrintBeginFrameBanner = true;
              } //导航到新路由
              ,
            ),
            TextButton(
              child: Text("我们也可以通过设置 debugPaintSizeEnabled 为true以可视方式调试布局问题"),
              onPressed: () {
                debugPaintSizeEnabled = true;
              } //导航到新路由
              ,
            ),
          ],
        ),
      )),

      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),

      bottomNavigationBar: BottomNavigationBar(
        // 底部导航
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
          BottomNavigationBarItem(
              icon: Icon(Icons.business), label: 'Business'),
          BottomNavigationBarItem(icon: Icon(Icons.school), label: 'School'),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.blue,
        onTap: _onItemTapped,
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
      drawer: MyDrawer(),
    );
  }
}

class NewRoute extends StatelessWidget {
  NewRoute({
    Key? key,
    required this.text, // 接收一个text参数
  }) : super(key: key);

  final String text;

  var routText = "";

  Color? getColor(Set<MaterialState> states) {
    if (states.contains(MaterialState.focused) &&
        !states.contains(MaterialState.pressed)) {
      //获取焦点时的颜色
      return Colors.blue;
    } else if (states.contains(MaterialState.pressed)) {
      //按下时的颜色
      return Colors.deepPurple;
    }
    //默认状态使用灰色
    return Colors.grey;
  }

  @override
  Widget build(BuildContext context) {
    //获取路由参数
    var args = ModalRoute.of(context)?.settings.arguments;
    print("路由表传递的值: $args");
    if (args != null) {
      routText = args.toString();
    } else {
      routText = text;
    }

    return Scaffold(
      appBar: AppBar(
        title: Text("New route"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(routText),
            TextButton(
              child: Text('自定义样式文本按钮'),
              style: ButtonStyle(
                //定义文本的样式 这里设置的颜色是不起作用的
                textStyle: MaterialStateProperty.all(
                    TextStyle(fontSize: 18, color: Colors.red)),
                //设置按钮上字体与图标的颜色
                //foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
                //更优美的方式来设置
                foregroundColor: MaterialStateProperty.resolveWith(
                  (states) {
                    if (states.contains(MaterialState.focused) &&
                        !states.contains(MaterialState.pressed)) {
                      //获取焦点时的颜色
                      return Colors.blue;
                    } else if (states.contains(MaterialState.pressed)) {
                      //按下时的颜色
                      return Colors.deepPurple;
                    }
                    //默认状态使用灰色
                    return Colors.grey;
                  },
                ),
                //背景颜色
                backgroundColor: MaterialStateProperty.resolveWith((states) {
                  //设置按下时的背景颜色
                  if (states.contains(MaterialState.pressed)) {
                    return Colors.blue[200];
                  }
                  //默认不使用背景颜色
                  return null;
                }),
                //设置水波纹颜色
                overlayColor: MaterialStateProperty.all(Colors.yellow),
                //设置阴影  不适用于这里的TextButton
                elevation: MaterialStateProperty.all(0),
                //设置按钮内边距
                padding: MaterialStateProperty.all(EdgeInsets.all(10)),
                //设置按钮的大小
                minimumSize: MaterialStateProperty.all(Size(200, 100)),
                //设置边框
                side: MaterialStateProperty.all(
                    BorderSide(color: Colors.grey, width: 1)),
                //外边框装饰 会覆盖 side 配置的样式
                shape: MaterialStateProperty.all(StadiumBorder()),
              ),
              onPressed: () {},
            ),
            OutlinedButton.icon(
              onPressed: () => Navigator.pop(context, "我是返回值1"),
              icon: Image.network(
                "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4",
                width: 100.0,
                color: Colors.blue,
                colorBlendMode: BlendMode.difference,
              ),
              label: Text("返回"),
            ),
            OutlinedButton(
              onPressed: () => Navigator.pop(context, "我是返回值2"),
              child: Text("返回"),
              style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.resolveWith(getColor)),
            ),
            IconButton(
              icon: Icon(
                Icons.thumb_up,
                color: Color(0xFFA0951D),
              ),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}

class MyDrawer extends StatelessWidget {
  const MyDrawer({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: MediaQuery.removePadding(
        context: context,
        //移除抽屉菜单顶部默认留白
        removeTop: true,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 38.0),
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                    child: ClipOval(
                      child: Image.asset(
                        "ic_bind_card_focus.png",
                        width: 80,
                      ),
                    ),
                  ),
                  Text(
                    "Wendux",
                    style: TextStyle(fontWeight: FontWeight.bold),
                  )
                ],
              ),
            ),
            Expanded(
              child: ListView(
                children: <Widget>[
                  ListTile(
                    leading: const Icon(Icons.add),
                    title: const Text('Add account'),
                  ),
                  ListTile(
                    leading: const Icon(Icons.settings),
                    title: const Text('Manage accounts'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
